const { db, query } = require("../../db/db");
const util = require("util");
const { URL } = require("url");
const moment = require("moment");
const axios = require("axios");
const cheerio = require("cheerio");
function isValidURL(urlString) {
  try {
    new URL(urlString);
    return true;
  } catch (_) {
    return false;
  }
}
async function getTitleAndImage(url) {
  try {
    // 发送GET请求获取网页内容
    const { data } = await axios.get(url);

    // 解析URL获取原站点域名
    const parsedUrl = new URL(url);
    const domain = parsedUrl.hostname;
    // 使用cheerio加载网页数据
    const $ = cheerio.load(data);

    // 提取标题
    const title = $("title").text();

    // 提取头图，这里假设是第一个<img>标签的src属性
    const image = $("img").first().attr("src");

    return { title, image, domain };
  } catch (error) {
    console.error("An error occurred:", error);
    return null;
  }
}
async function AnalysisUrl(req, res) {
  const url = req.body.url;
  if (!isValidURL(url)) {
    res.send({
      status: 1,
      msg: "请输入正确的url",
    });
  } else {
    const resRet = await getTitleAndImage(url);
    res.send({
      status: 0,
      urlTitle: resRet ? resRet.title : req.body.url,
      urlImage: resRet ? resRet.image : "",
      domain: resRet ? resRet.domain : "",
    });
  }
}

module.exports = { AnalysisUrl };
